<template>
    <div class="file-class">
        <div class="page-action-btn">
            <el-button type="primary" v-if="UIAuth._api_admin_folder_post" @click="showAdd()">添加文件夹</el-button>
            <el-button type="warning" v-if="UIAuth._api_admin_folder_put" @click="showEdit">修改</el-button>
            <p-confirm-btn @confirm="del" v-if="UIAuth._api_admin_folder_delete"></p-confirm-btn>
        </div>
        <div v-if="UIAuth._api_admin_folder_get">
            <p-table-tree ref="pTableTree" v-loading="loading" :data="dataList" :sub-height="134" :show-paginate="false" @row-click="rowClick" @row-dblclick="showEdit" @row-clear="rowClear"
                @selection-change="selectionChange">
                <el-table-column prop="folder_name" label="名称" min-width="200"></el-table-column>
                <el-table-column prop="visit" label="访问权限" width="100" v-if="filesAuthOpen">
                    <template v-slot="{ row }">
                        <div v-if="!row.pid">
                            <api-visit :visit="row.visit"></api-visit>
                        </div>
                        <div v-else>
                            <i class="el-icon-top" style="font-size: 16px"></i>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="sort" label="排序" width="80"></el-table-column>
            </p-table-tree>
        </div>
        <p-el-dialog v-model="showDialog" top="10vh" :title="`${getBtnName}文件夹`" width="500px" @close="dialogClose" @confirm="isEdit ? edit() : add()" :ok-text="getBtnName">
            <el-form :model="params" status-icon :rules="paramsRules" ref="elForm" label-width="120px">
                <el-form-item label="上级文件夹">
                    <folder-tree-select v-model="params.pid" />
                </el-form-item>
                <el-form-item label="名称" prop="folder_name">
                    <el-input v-model="params.folder_name" placeholder="文件夹名称"></el-input>
                </el-form-item>
                <div v-if="filesAuthOpen && !params.pid">
                    <div style="color: #b67676; font-size: 12px">
                        向下继承，子文件夹和文件拥有根父文件夹所有的权限角色和权限（只有根文件夹可设置）
                    </div>
                    <el-form-item label="访问权限">
                        <el-radio-group v-model="params.visit" size="small">
                            <el-radio-button :label="apiAuth.PUBLIC">{{ apiAuthName[apiAuth.PUBLIC]}}</el-radio-button>
                            <el-radio-button :label="apiAuth.LOGIN">{{ apiAuthName[apiAuth.LOGIN] }}</el-radio-button>
                            <el-radio-button :label="apiAuth.AUTH">{{ apiAuthName[apiAuth.AUTH]  }}</el-radio-button>
                            <el-radio-button :label="apiAuth.SYSTEM">{{ apiAuthName[apiAuth.SYSTEM]}}</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="权限角色" v-if="params.visit == apiAuth.AUTH">
                        <div v-for="item in params.roles" :key="item.auth_group_id">
                            <el-form-item :label="getAuthGroupTitle(item.auth_group_id)" label-width="60px">
                                <el-select v-model="item.roles" placeholder="请选择权限角色" multiple style="width: 100%">
                                    <el-option v-for="rItem in authGroupGetRolesList(item.auth_group_id)" :key="rItem.id" :label="rItem.role_name" :value="rItem.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                    </el-form-item>
                </div>
                <el-form-item label="排序">
                    <el-input v-model="params.sort" placeholder="排序"></el-input>
                </el-form-item>
            </el-form>
        </p-el-dialog>
    </div>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, ref, toRefs } from "vue";
import { useStore } from "vuex";
import { IPaginate, defaultPaginate } from "@/lib/IApp";
import PElDialog from "@/components/PElDialog.vue";
import valid from "@/lib/valid";
import http from "@/lib/http/http";
import PConfirmBtn from "@/components/PConfirmBtn.vue";
import message from "@/lib/message";
import utils from "@/lib/utils";
import PTableTree from "@/components/PTableTree.vue";
import config from "@/config";
import TreeTool from "@/lib/TreeTool";
import FolderTreeSelect from "@/components/file/FolderTreeSelect.vue";
import ApiAuth, { ApiAuthName } from "@/lib/apiRoute/apiRoute";
import ApiVisit from "@/components/api/ApiVisit.vue";
/**
 * state 数据类型
 */
interface IState {
    loading: boolean;
    /**
     * 数据列表
     */
    dataList: any[];
    /**
     * 是否显示 添加编辑窗口
     */
    showDialog: boolean;
    /**
     * 是否修改
     */
    isEdit: boolean;
    /**
     * http 请求参数
     */
    params: any;
    /**
     * 单选选择的行内容
     */
    tableRow: any;
    /**
     * 多选选择的行内容
     */
    tableRows: any[];
    /**
     * 查询条件
     */
    search: any;
    /**
     * 权限角色列表
     */
    rolesList: any[];
    /**
     * 权限组列表
     */
    authGroupList: any[];
    /**
     * 修改之前的pid
     */
    oldPid: string;
}
const ParamsRules: any = {
    folder_name: [
        { required: true, message: "请输入文件夹名称", trigger: ["blur"] },
    ],
};
const defaultParams = { roles: [] };
export default defineComponent({
    name: "FileClass",
    components: {
        PElDialog,
        PConfirmBtn,
        PTableTree,
        FolderTreeSelect,
        ApiVisit,
    },
    emits: [],
    setup() {
        const store = useStore();
        const { UIAuth, bodySize } = toRefs(store.state);
        const treeTool: TreeTool = new TreeTool();
        const elForm: any = ref<any>();
        const pTableTree: any = ref<any>();
        const state = reactive<IState>({
            loading: false,
            dataList: [],
            showDialog: false,
            isEdit: false,
            params: {},
            tableRow: null,
            tableRows: [],
            search: {},
            rolesList: [],
            authGroupList: [],
            oldPid: "",
        });
        /**
         * 单击选中
         */
        const rowClick = (val: any) => {
            state.tableRow = val.row;
        };
        /**
         * 取消选中
         */
        const rowClear = () => {
            state.tableRow = null;
        };
        /**
         * 关闭添加修改窗口
         */
        const dialogClose = (showDialog: boolean = false) => {
            state.params = utils.CopyNewObject(defaultParams);
            state.oldPid = "";
            state.isEdit = showDialog;
            state.showDialog = showDialog;
        };
        /**
         * 多选时触发
         */
        const selectionChange = (val: any[]) => {
            state.tableRows = val;
        };
        /**
         * 通过权限组ID获取 权限角色列表
         */
        const authGroupGetRolesList = (id: string): any[] => {
            const res: any[] = [];
            for (const item of state.rolesList) {
                if (item.auth_group_id === id) {
                    res.push(item);
                }
            }
            return res;
        };
        /**
         * 获取权限组内容
         */
        const getAuthGroupList = () => {
            state.loading = true;
            http.Get(`/auth-group/share-id`)
                .then((data) => {
                    const shareId = data;
                    http.Get(`/auth-group`)
                        .then((dataList) => {
                            state.authGroupList = [];
                            dataList.forEach((item: any) => {
                                if (item.id !== shareId) {
                                    state.authGroupList.push(item);
                                }
                            });
                        })
                        .catch((err) => false);
                })
                .catch((err) => false);
        };
        /**
         * 获取权限角色内容
         */
        const getRolesList = () => {
            http.Get(`/roles`)
                .then((data) => {
                    state.rolesList = data;
                })
                .catch((err) => false);
        };
        /**
         * 获取权限组名称
         */
        const getAuthGroupTitle = (val: string): string => {
            let label = "";
            for (const item of state.authGroupList) {
                if (item.id === val) {
                    label = item.title;
                    break;
                }
            }
            return label;
        };
        /**
         * 初始化 参数中的权限
         */
        const initParamsRoles = (oldData: any = null) => {
            const rolesList = [];
            const temMap: Map<string, []> = new Map<string, []>();
            if (!utils.empty(oldData)) {
                for (const item of oldData) {
                    temMap.set(item.auth_group_id, item.roles);
                }
            }
            for (const item of state.authGroupList) {
                let roles = temMap.get(item.id);
                if (utils.empty(roles)) {
                    roles = [];
                }
                rolesList.push({ auth_group_id: item.id, roles });
            }
            state.params.roles = rolesList;
        };
        /**
         * 显示添加
         */
        const showAdd = (isChile: boolean = true) => {
            let pId = "";
            if (state.tableRow != null) {
                pId = state.tableRow.id;
            }
            state.oldPid = pId;
            state.params = {
                pid: pId,
                visit: 1,
                roles: [],
                sort: 1,
            };
            initParamsRoles(null);
            state.isEdit = false;
            state.showDialog = true;
        };
        /**
         * 获取内容
         */
        const getList = () => {
            state.loading = true;
            http.Get(`/folder`, state.search)
                .then((data) => {
                    state.dataList = treeTool.listToTree(data, "");
                    state.loading = false;
                })
                .catch((err) => (state.loading = false));
        };
        /**
         * 添加
         */
        const add = () => {
            elForm.value.validate((ok: boolean) => {
                if (ok) {
                    http.Post("/folder", state.params)
                        .then((data) => {
                            if (utils.empty(state.dataList)) {
                                state.dataList = [data];
                            } else {
                                treeTool.add(state.dataList, data);
                            }
                            dialogClose();
                        })
                        .catch((err) => "");
                } else {
                    return false;
                }
            });
        };
        /**
         * 显示修改
         */
        const showEdit = () => {
            if (state.tableRow == null) {
                message.error("请选择要修改的数据");
                return;
            }
            state.isEdit = true;
            state.params.folder_name = state.tableRow.folder_name;
            state.params.visit = state.tableRow.visit;
            state.params.sort = state.tableRow.sort;
            initParamsRoles(state.tableRow.roles);
            state.oldPid = state.tableRow.pid;
            state.params.pid = state.tableRow.pid;
            state.params.id = state.tableRow.id;
            state.params.version = state.tableRow.version;
            state.showDialog = true;
        };
        /**
         * 修改
         */
        const edit = () => {
            elForm.value.validate((ok: boolean) => {
                if (ok) {
                    http.Put("/folder", state.params)
                        .then((data) => {
                            treeTool.edit(state.dataList, data);
                            if (state.oldPid !== data.pid) {
                                let temData = treeTool.get(
                                    state.dataList,
                                    data.id
                                );
                                if (utils.empty(temData)) {
                                    temData = data;
                                }
                                treeTool.delete(state.dataList, data.id);
                                treeTool.add(state.dataList, temData);
                            }
                            dialogClose();
                        })
                        .catch((err) => "");
                } else {
                    return false;
                }
            });
        };
        /**
         * 删除
         */
        const del = () => {
            const ids: string[] = [];
            if (state.tableRows.length === 0) {
                if (state.tableRow == null) {
                    message.error("请选择要删除的数据");
                    return;
                } else {
                    ids.push(state.tableRow.id);
                }
            }
            let isDelete = true;
            state.tableRows.forEach((item) => {
                if (!utils.empty(item.children) && item.children.length > 0) {
                    isDelete = false;
                    return;
                }
                ids.push(item.id);
            });
            if (!isDelete) {
                message.error("删除的【文件夹】中存在子文件夹");
                return;
            }
            message.loadingShow("删除中");
            http.Delete("/folder", { ids })
                .then((data) => {
                    state.tableRow = null;
                    state.tableRows = [];
                    treeTool.deletes(state.dataList, ids);
                    pTableTree.value.clearSelect();
                })
                .catch((err) => false);
        };
        getAuthGroupList();
        getRolesList();
        getList();
        return {
            UIAuth,
            bodySize,
            apiAuth: ApiAuth,
            apiAuthName: ApiAuthName,
            filesAuthOpen: config.filesAuthOpen,
            paramsRules: ParamsRules,
            elForm,
            pTableTree,
            ...toRefs(state),
            rowClick,
            rowClear,
            dialogClose,
            selectionChange,
            authGroupGetRolesList,
            getAuthGroupList,
            getAuthGroupTitle,
            showAdd,
            add,
            showEdit,
            edit,
            del,
            getBtnName: computed(() => (state.isEdit ? "修改" : "添加")),
        };
    },
});
</script>

<style scoped lang="scss">
</style>
